package com.easyskool.services.core;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.easyskool.composer.UserServiceComposer;
import com.easyskool.constants.CommonConstants;
import com.easyskool.constants.MessageConstants;
import com.easyskool.hibernate.model.ContactForms;
import com.easyskool.hibernate.model.Schools;
import com.easyskool.hibernate.model.UserAuthorization;
import com.easyskool.util.mailUtil;
//import com.easyskool.hibernate.model.AccessAuthorization;
import com.easyskool.utilfunction.UtilFunctions;
import com.ivp.cloud.stratus.logger.LoggingUtil;
import com.sun.jersey.spi.container.servlet.PerSession;

@Path("/userauthservice")
@PerSession
public class UserAuthenticationService implements Serializable {

	UserServiceComposer userService = new UserServiceComposer();
	private static LoggingUtil logger = (LoggingUtil) LoggingUtil
			.getLogger(UserAuthenticationService.class.getName());

	/**
	 * Validates the credentials o fa user who is signing in
	 * {"user":"ishu","password":"ishu"}
	 * @param user
	 * @param password
	 * @param req
	 *            --Servlet Request
	 * @return Response to be sent to UI
	 * @throws JSONException
	 * @throws Exception
	 */
	@Path("/validateCredentails")
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public Response validateCredentails(String credentials,
			@Context HttpServletRequest req) throws JSONException {
		try {
			JSONObject json = new JSONObject(credentials);
			UserAuthorization user = userService.validateCredentials(
					json.getString("user"), json.getString("password"));
			
			
			if (user != null)
				{String ag=user.getAccessGroups()
				.getAgName();
				HttpSession  session = req.getSession(true);
				session.setAttribute(CommonConstants.ACCESS_GROUPS, ag);
				session.setAttribute(CommonConstants.USERCODE, user.getUaCode());
				Schools school=user.getSchools();
				session.setAttribute(CommonConstants.SCHOOL_CODE, school);
				session.setAttribute("defaultPage", CommonConstants.REDIRECT_URL2);
				}
			else {
				return UtilFunctions.createSuccessResponse(200,
						CommonConstants.OPERATION, CommonConstants.ERROR_);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return UtilFunctions.createSuccessResponse(200,
					CommonConstants.OPERATION, CommonConstants.ERROR_);
		}
		System.out.println(credentials + "STRinggg");
		return UtilFunctions.createSuccessResponse(200,
				CommonConstants.OPERATION, CommonConstants.REDIRECT_URL);
	}

	@Path("/checkrest")
	@POST
	@Produces("application/json")
	public Response checkrest(@QueryParam("user") String user,
			@QueryParam("whereClause") String whereClause,
			@Context HttpServletRequest req) throws JSONException {
		System.out.println(req.getContextPath() + " " + req.getRequestURI());
		System.out.println("Its working Bruah Bruah");
		return UtilFunctions.createSuccessResponse(200,
				CommonConstants.OPERATION, CommonConstants.SUCCESS);
	}
	@Path("/getUncontacted")
	@POST
	@Produces("application/json")
	public Response getUncontacted(	@Context HttpServletRequest req) throws Exception {
		List<ContactForms> contacts=	userService.getUncontacted();
		if(contacts.size()==0||contacts==null)
		{
			System.out.println("No record retrieved");
			return UtilFunctions.createSuccessCustomResponse(500,
					CommonConstants.OPERATION, CommonConstants.ERROR);
		}
		JSONArray ja =new JSONArray();
		for(int i=0;i<contacts.size();i++)
		{
			JSONObject jo =new JSONObject();
			jo.put("rowId", contacts.get(i).getRowId());
			jo.put("cfName", contacts.get(i).getCfName());
			jo.put("cfMobile", contacts.get(i).getCfMobile());
			jo.put("cfEmail", contacts.get(i).getCfEmail());
			jo.put("cfReason", contacts.get(i).getCfReason());
			jo.put("cfNeedAdvertisement", contacts.get(i).getCfNeedAdvertisement());
			jo.put("uaCode", contacts.get(i).getUaCode());
			jo.put("cfType", contacts.get(i).getCfType());
			
			ja.put(jo);
			
		}
		System.out.println(ja.toString());
		return UtilFunctions.createObjectResponse(200,
			  ja.toString());
	}

	 /**
	 * calls composer to insert school request
	 * @param user
	 * @param insertValues
	 * @return response for the UI
	 * @throws Exception
	 */
	 @Path("/insertRequest")
	 @POST
	 @Produces("application/json")
	 public Response insertRequest( String dataStr)
	 throws Exception{
	 logger.info("Entering insertSchoolRequest" );
	 boolean result = false;
	 JSONObject json = new JSONObject(dataStr);
	 String formData=json.getString("fields");
	 System.out.println("formData : "+formData);
 	 result = userService.insertRequest(  formData);
	
	 logger.info("Exiting insertSchoolRequest" );
	 if (result)
	 return UtilFunctions.createSuccessResponse(200,
				CommonConstants.OPERATION, CommonConstants.SUCCESS);
	 else
		 return UtilFunctions.createSuccessResponse(200,
					CommonConstants.OPERATION, CommonConstants.FAIL); 
	 }
	/**
	 * sets the roles of a user in the session
	 * 
	 * @param session
	 * @param user
	 * @param result
	 * @throws Exception
	 */
	// @SuppressWarnings("rawtypes")
	// public void validateAccess(HttpSession session,AccessAuthorization
	// result) throws Exception {
	// System.out.println("Validate access in UserAuthService "+"result :"+result);
	// try{
	//
	// session.setAttribute(CommonConstants.USERNAME,result.getAaEmail());
	// session.setAttribute(CommonConstants.SCHOOL_CODE,result.getAaSchoolCode()
	// );
	//
	//
	// session.setAttribute(CommonConstants.ROLE,result.getAaPriviledgeLevel());
	// }catch(Exception e){
	// e.printStackTrace();
	// throw e;
	// }
	//
	// }
	//
	// @Path("/insertUser")
	// @POST
	// @Produces("application/json")
	// public Response insertUser(@QueryParam("user") String user,
	// @QueryParam("fields") String insertValues)
	// throws Exception{
	// String result = null;
	// // LoginDao loginDao = new LoginDao();
	// // List<TAccessAuthorization> result = loginDao.list(user, password);
	// System.out.println("user : "+user+ " fields : "+insertValues );
	// result = userService.insertUser(user, insertValues);
	//
	// System.out.println("result : "+result);
	// return Response.status(200).entity(result).build();
	// }
	//
	// /**
	// * Logs out the user by clearing the session
	// * @param req
	// * @return
	// * @throws Exception
	// */
	// @Path("/logout")
	// @POST
	// @Produces("application/json")
	// public Response logout(@Context HttpServletRequest req)
	//
	// throws Exception{
	// String result="";
	// try
	// {
	// HttpSession session= req.getSession(false);
	// System.out.println("USER: "+session.getAttribute("username"));
	// String user=(String)session.getAttribute("username");
	// session.invalidate();
	// if(user==null)
	// result=UtilFunctions.createJsonObject(MessageConstants.LOGOUT,
	// MessageConstants.LOGGEDOUT);
	// else
	// result=UtilFunctions.createJsonObject(MessageConstants.LOGOUT,
	// MessageConstants.SUCCESS);
	// System.out.println(result+" RESULT");
	// System.out.println("result in logout: "+result);
	// }
	// catch(Exception e)
	// {
	// System.out.println(e);
	// result=UtilFunctions.createJsonObject(MessageConstants.LOGOUT,
	// MessageConstants.LOGOUTFAIL);
	// }
	//
	// return Response.status(200).entity(result).build();
	// }
	//

	// /**
	// * gets the data of requests which have neither been rejected nor accepted
	// * @param user
	// * @param whereClause
	// * @return
	// * @throws JSONException
	// * @throws Exception
	// */
	// @Path("/setDetails")
	// @POST
	// @Produces("application/json")
	// public Response setDetails(@QueryParam("user") String user,
	// @QueryParam("updateClause") String whereClause,
	// @QueryParam("whereClause") String updateClause,
	// @Context HttpServletRequest req) throws JSONException {
	// System.out.println("Data Coming in  setDetails Service "+user+" :USER "+whereClause+" :whereClause "+
	// updateClause+" :updateClause");
	// String result = null;
	// user=UtilFunctions.getUserName(req);
	// try
	// {
	// result = userService.setDetails(user,updateClause,whereClause);
	// System.out.println("result : " + result);
	// if(CommonConstants.SUCCESS.equals(result))
	// return UtilFunctions.createSuccessResponse(200,
	// CommonConstants.UPDATE, CommonConstants.SUCCESS) ;
	// else
	// return UtilFunctions.createErrorResponse(200,
	// CommonConstants.UPDATE, CommonConstants.FAIL);
	// }
	// catch (Exception e)
	// {
	// e.printStackTrace();
	// return UtilFunctions.createErrorResponse(200,
	// CommonConstants.UPDATE, CommonConstants.FAIL);
	// }
	// }
	//
	// /**
	// * Validates the credentials o fa user who is signing in
	// * @param user
	// * @param password
	// * @param req--Servlet Request
	// * @return Response to be sent to UI
	// * @throws JSONException
	// * @throws Exception
	// */
	// @Path("/sendPasswordDetails")
	// @POST
	// @Produces("application/json")
	// public Response sendPasswordDetails(@QueryParam("user") String user,
	// @QueryParam("whereClause") String whereClause,
	// @Context HttpServletRequest req) throws JSONException
	// {
	// try{
	// System.out.println("Data coming in sendPassord Composer: "+
	// user+" :user "+whereClause+" :whereClause");
	// int result=userService.sendPassword(user,whereClause);
	// if(result==1)
	// { System.out.println("Data coming out of sendPasswordDetails service1"+
	// result);
	// return UtilFunctions.createSuccessResponse(200,
	// CommonConstants.OPERATION, CommonConstants.SUCCESS) ;
	// }
	// else if(result==0)
	// {System.out.println("Data coming out of sendPasswordDetails service2"+
	// result);
	// return UtilFunctions.createSuccessResponse(200,
	// CommonConstants.OPERATION, CommonConstants.NOT_FOUND) ;
	// }
	// else if(result==-1)
	// {System.out.println("Data coming out of sendPasswordDetails service3"+
	// result);
	// return UtilFunctions.createSuccessResponse(200,
	// CommonConstants.OPERATION, CommonConstants.ERROR) ;
	// }
	// }
	// catch(Exception e )
	// {
	// System.out.println("Exception in Service");
	// e.printStackTrace();
	// return UtilFunctions.createSuccessResponse(200,
	// CommonConstants.OPERATION, CommonConstants.ERROR) ;
	// }
	// return null;
	// }
	// /**
	// * Validates the credentials o fa user who is signing in
	// * @param user
	// * @param password
	// * @param req--Servlet Request
	// * @return Response to be sent to UI
	// * @throws JSONException
	// * @throws Exception
	// */
	// @Path("/changePasswordDetails")
	// @POST
	// @Produces("application/json")
	// public Response changePasswordDetails(@QueryParam("user") String user,
	// @QueryParam("whereClause") String whereClause,
	// @Context HttpServletRequest req) throws JSONException
	// {
	// try{
	// System.out.println("Data coming in changePasswordDetails Service: "+
	// user+" :user "+whereClause+" :whereClause");
	// int result=userService.changePasswordDetails(user,whereClause);
	// if(result==1)
	// { System.out.println("Data coming out of changePasswordDetails service1"+
	// result);
	// return UtilFunctions.createSuccessResponse(200,
	// CommonConstants.OPERATION, CommonConstants.SUCCESS) ;
	// }
	//
	// else if(result==-1)
	// {System.out.println("Data coming out of changePasswordDetails service3"+
	// result);
	// return UtilFunctions.createSuccessResponse(200,
	// CommonConstants.OPERATION, CommonConstants.ERROR_) ;
	// }
	// }
	// catch(Exception e )
	// {
	// System.out.println("Exception in Service");
	// e.printStackTrace();
	// return UtilFunctions.createSuccessResponse(200,
	// CommonConstants.OPERATION, CommonConstants.ERROR) ;
	// }
	// return null;
	// }
	//
	//
}
